package demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Javen
 * CAS
 * ABA  ->   AtomicStampedReference
 * 自旋锁
 */
@Slf4j
public class SpinLockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        log.info("{} come in", Thread.currentThread().getName());
        while (!atomicReference.compareAndSet(null, thread)) {

        }
    }

    public void myUnlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        log.info("{} invoked myUnlock", Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        final SpinLockDemo spin = new SpinLockDemo();

        new Thread(() -> {
            spin.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
                spin.myUnlock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1").start();


        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            spin.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
                spin.myUnlock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2").start();

    }
}
